package com.example.bianpan;

import com.example.bianpan.context.Context;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
public class ProcessInstance<C extends Context,R> {
    /**
     * 用于生成一个流程context
     */
    private Supplier<C> contextBuilder;

    /**
     * 被流程节点处理完成 context， 使用这个resultBuilder转换为调用者指定的结果
     */
    private Function<C,R> resultBuilder;

    private String operation;

    private  ProcessEngin processEngin;

    public  static  final  Function NO_RESULT = (c) -> null;


    ProcessInstance(String operation,ProcessEngin processEngin)
    {
        this.operation=operation;
        this.processEngin=processEngin;
    }

    public  ProcessInstance<C,R> contextBuilder(Supplier<C> contextBuilder)
    {
        this.contextBuilder = contextBuilder;
        return this;
    }


    public  ProcessInstance<C,R> resultBuilder(Function<C,R> resultBuilder)
    {
        this.resultBuilder = resultBuilder;
        return this;
    }

    public  ProcessInstance<C,R> noResultRequired()
    {
        this.resultBuilder = NO_RESULT;
        return this;
    }

    /**
     * 执行流程引擎，返回预期结果类型
     */
    public R run()
    {
        Assert.isTrue(contextBuilder!=null);
        Assert.isTrue(resultBuilder!=null);
        Assert.isTrue(operation!=null);
        C context = contextBuilder.get();
        processEngin.process(operation,context);
        return  resultBuilder.apply(context);

    }


}
